package com.lht.femalecat.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author:骆宏图
 * @CreateDate: 16:12 2018/7/26.
 * @Description:
 * @Modified By:
 */
public class TimeClientHandler implements Runnable{

    private Selector selector;

    private SocketChannel socketChannel;

    private String host;

    private int port;

    private volatile boolean  stop;


    public TimeClientHandler(String host, int port) {
        this.host = host;
        this.port = port;

        try {
            selector=Selector.open();
            socketChannel=SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }




    @Override
    public void run() {

        try {
            doConnect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        while(!stop){
            try {
                selector.select(1000);
                Set<SelectionKey> keySet=selector.selectedKeys();
                Iterator<SelectionKey> it=keySet.iterator();
                SelectionKey key=null;
                while(it.hasNext()){
                    key=it.next();
                    it.remove();
                    try{
                        handleInput(key);
                    }catch (Exception e) {
                        e.printStackTrace();
                        if (key != null) {
                            key.cancel();
                            if (key.channel() != null) {
                                key.channel().close();
                            }
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

    }


    private void handleInput(SelectionKey key) throws IOException{
        if(key.isValid()){
            //判断是否连接成功
            SocketChannel channel=(SocketChannel)key.channel();
            if(key.isConnectable()){
                if(channel.finishConnect()){
                    channel.register(selector,SelectionKey.OP_READ);
                    doWrite();
                    System.out.println(selector.selectedKeys().size());
                }else{
                    System.exit(1);//连接失败，进程退出
                }
            }

            if(key.isReadable()){
                ByteBuffer readBuffer=ByteBuffer.allocate(1024);
                int readBytes=channel.read(readBuffer);
                if(readBytes>0){
                    readBuffer.flip();
                    byte[] bytes=new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body=new String(bytes,"UTF-8");
                    System.out.println("Now is :" +body);
                    this.stop=true;
                }else if(readBytes<0){
                    key.cancel();//关闭链路
                    channel.close();
                }else{
                    ;//读到0字节不做任何处理
                }
            }
        }

    }

    private  void doConnect() throws IOException {
        if (socketChannel.connect(new InetSocketAddress(host,port))){
            socketChannel.register(selector,SelectionKey.OP_READ);
            doWrite();
        }else{
            socketChannel.register(selector,SelectionKey.OP_CONNECT);
        }
    }

    private void doWrite() throws IOException {
        byte[] bytes="Query Time Order".getBytes();
        ByteBuffer writeBuffer=ByteBuffer.allocate(bytes.length);
        writeBuffer.put(bytes);
        writeBuffer.flip();
        socketChannel.write(writeBuffer);
        if(!writeBuffer.hasRemaining()){
            System.out.println("Send order 2 server successd.");
        }
    }
}
